package com.lcf.mytccaccount.threadlocal;

import java.util.HashMap;
import java.util.Map;

/**
 * http://ifeve.com/threadlocal%E4%BD%BF%E7%94%A8/
 */
public class TestThreadLocal {
    static ThreadLocal<HashMap> threadLocal = new ThreadLocal<HashMap>() {

        @Override
        protected HashMap initialValue() {
            System.out.println(Thread.currentThread().getName() + "initialValue");
            return new HashMap();
        }
    };

    static ThreadLocal<Integer> threadLocal2 = new ThreadLocal<Integer>(){

        @Override
        protected Integer initialValue() {
            return 0;
        }
    };


    public static class T1 implements Runnable {
        //        private final static Map map = new HashMap();
        private int aa = 0;
        int id;

        public T1(int id) {

            this.id = id;

        }

        public void run() {
            Map map = threadLocal.get();
            Integer integer = threadLocal2.get();
            for (int i = 0; i < 20; i++) {
                aa =+ 1;
                threadLocal2.set(aa);
                map.put(i, i + id * 100);
                try {
                    Thread.sleep(100);
                } catch (Exception ex) {
                }
            }

//            System.out.println(Thread.currentThread().getName() + "# map.size() =" + map.size() + " #" + map);
            System.out.println(Thread.currentThread().getName() + "# aa =" + aa);
        }
    }

    public static void main(String[] args) {

        Thread[] runs = new Thread[15];
        T1 t = new T1(1);
        for (int i = 0; i < runs.length; i++) {
            runs[i] = new Thread(t);
        }

        for (int i = 0; i < runs.length; i++) {
            runs[i].start();
        }

    }
}
